package com.example.service;

import com.example.mapper.MenuRoleMapper;
import com.example.mapper.RoleMapper;
import com.example.model.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 麦健豪
 * @date 2020/10/6 11:56
 */
@Service
public class RoleService {
    static final String ROLE_PREFIX = "ROLE_";
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    MenuRoleMapper menuRoleMapper;

    public List<Role> getAllRoles() {
        return roleMapper.getAllRoles();
    }

    public Integer addRole(Role role) {
        if (!role.getName().startsWith(ROLE_PREFIX)) {
            role.setName(ROLE_PREFIX + role.getName());
        }
        return roleMapper.insert(role);

    }

    @Transactional(rollbackFor = Exception.class)
    public Integer deleteRoleById(Integer rid) {
        //delete role need to delete menu_role about rid to mid at first
        menuRoleMapper.deleteByRid(rid);
        return roleMapper.deleteByPrimaryKey(rid);
    }
}
